google.load("maps", "2");
		
		var polylineAddresses = "";
		var map;
	    var directionsPanel;
	    var directions;
	    var directionsOptions;
	    var statuses;

		function initialize() 
		{
			map = new google.maps.Map2(document.getElementById("map"));
			map.setCenter(new google.maps.LatLng(-22.92632, -43.235147), 15);
		}

		google.setOnLoadCallback(initialize);

		function cleanName(streetName)
		{
			streetName = streetName.toLowerCase();

			streetName = streetName.replace("á","a");
			streetName = streetName.replace("à","a");
			streetName = streetName.replace("ã","a");
			streetName = streetName.replace("â","a");
			streetName = streetName.replace("ä","a");
			
			streetName = streetName.replace("é","e");
			streetName = streetName.replace("è","e");
			streetName = streetName.replace("ẽ","e");
			streetName = streetName.replace("ê","e");
			streetName = streetName.replace("ë","e");
			
			streetName = streetName.replace("í","i");
			streetName = streetName.replace("ì","i");
			streetName = streetName.replace("ĩ","i");
			streetName = streetName.replace("î","i");
			streetName = streetName.replace("ï","i");
			
			streetName = streetName.replace("ó","o");
			streetName = streetName.replace("ò","o");
			streetName = streetName.replace("õ","o");
			streetName = streetName.replace("ô","o");
			streetName = streetName.replace("ö","o");
			
			streetName = streetName.replace("ú","u");
			streetName = streetName.replace("ù","u");
			streetName = streetName.replace("ũ","u");
			streetName = streetName.replace("û","u");
			streetName = streetName.replace("ü","u");
			
			streetName = streetName.replace("ç","c");
			
			streetName = streetName.replace(" ","");
			streetName = streetName.replace(",","");
			streetName = streetName.replace(".","");
			streetName = streetName.replace(";","");
			
			return streetName; 
		}

		function trim(str) 
		{
			return str.replace(/^\s+|\s+$/g,"");
		}

		function translateNames(streetName)
		{
			var streetTranslate = new Array();
			
			streetName = trim(streetName);

			streetTranslate['av. aterro do flamengo'] = 'aterro do flamengo';
			streetTranslate['av. das américas'] = 'av. das améicas';
			streetTranslate['avenida delfim moreira'] = 'av. delfim moreira';
			streetTranslate['av. embaixador abelardo bueno'] = 'av. emb. abelardo bueno';
			streetTranslate['avenida franklin roosevelt'] = 'av. franklin roosevelt';
			streetTranslate['av. mal. rondon'] = 'av. mal rondom';
			streetTranslate['av. min. ivan lins'] = 'av. ministro ivan lins';
			streetTranslate['av. ns. de copacabana'] = 'av. nossa senhora de copacabana';
			streetTranslate['av. pres. antônio carlos'] = 'av. presidente antônio carlos';
			streetTranslate['av. pres. vargas'] = 'av. presidente vargas';
			streetTranslate['av. pres. wilson'] = 'av. presidente wilson';
			streetTranslate['r. primeiro de março'] = 'av. primeiro de março';
			streetTranslate['avenida republica do paraguai'] = 'av. república do paraguai';
			streetTranslate['av. vieira souto'] = 'av. vieira souto';
			streetTranslate['r. visc. de pirajá'] = 'av. visconde de pirajá';
			streetTranslate['boulevard vinte e oito de setembro'] = 'boulevard 28 de setembro';
			streetTranslate['r. do cantagalo'] = 'corte do cantagalo';
			streetTranslate['av. aterro do flamengo'] = 'praia do flamengo';
			streetTranslate['av. pres. castelo branco'] = 'radial oeste';
			streetTranslate['r. bela vista'] = 'r. da bela vista';
			streetTranslate['r. gen. belegarde'] = 'r. gal. belegarde';
			streetTranslate['av. lauro sodré'] = 'r. lauro sodré';
			streetTranslate['av. prof. pereira reis'] = 'r. professor pereira reis';
			streetTranslate['av. são clemente'] = 'r. são clemente';
			streetTranslate['r. teixeira freitas'] = 'r. teixeira de freitas';
			streetTranslate['r. visc. rio branco'] = 'r. visconde do rio branco';
			streetTranslate['vd. ana nery'] = 'viaduto ana néri';
			streetTranslate['r. francisco eugenio, 1'] = 'descida da linha vermelha';
			streetTranslate['r. venceslau braz'] = 'av. venceslau brás';
			streetTranslate['r. são luiz gonzaga'] = 'largo da cancela';
			streetTranslate['av. osvaldo aranha'] = 'praça da bandeira';
			streetTranslate['?'] = 'trevo das forças armadas';
			streetTranslate['??'] = 'viaduto de todos os santos';
			
			if(streetTranslate[streetName])
				return streetTranslate[streetName];
			else
				return streetName;
		}

		function getTrafficStatus()
		{
			var statuses;
			var url = "http://localhost:8080/TrafficTipService/street/status";			 
			
			if (window.XMLHttpRequest) // code for IE7+, Firefox, Chrome, Opera, Safari
				xmlhttp = new XMLHttpRequest();
			else // code for IE6, IE5
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			
			if(!xmlhttp)
			{
				alert("Nao foi possivel criar um XMLHttpRequest!");
				return false;
			}			

			xmlhttp.open("GET",url,false);
			xmlhttp.send(null);
			
			statuses = eval( "(" + xmlhttp.responseText + ")" );			
			
			return statuses;
		}

		function getColor(streetName)
		{
			streetName = streetName.toLowerCase();
			streetName = trim(streetName);
			
			//alert(streetName + " : " + translateNames(streetName) + "->" + statuses.status[translateNames(streetName)]);
		
			if(statuses.status[translateNames(streetName)])
				return statuses.status["" + translateNames(streetName) + "" ];
			else
				return "#666666";
		}		

		function route()
		{
			statuses = getTrafficStatus();
			map = new google.maps.Map2(document.getElementById("map"));
			directionsOptions = {locale: "pt_BR" , getPolyline: true };			
			
			directionsPanel = document.getElementById("route");
			
			directionsPanel.innerHTML = "<h2>Descrição da rota</h2>";
			directionsPanel.style.visibility = "visible";
			directions = new GDirections(null, directionsPanel);
			directions.load("from: " + document.getElementById("origin").value + "+-+Rio+de+Janeiro+-+RJ+-+Brasil to: " + document.getElementById("destination").value + "+-+Rio+de+Janeiro+-+RJ+-+Brasil", directionsOptions);		
			GEvent.addListener(directions,"load", function(){ 
			
				if(directions.getStatus().code != 200)
				{
					alert("Erro ao executar consulta: código http " + directions.getStatus().code + " retornado pelo servidor da CET-RIO.");
					return false;
				}
				
				//alert("Listener retornou 200");
			
				//alert("Total de rotas: " + directions.getNumRoutes());
				
				var polyline = directions.getPolyline();
				var groute = directions.getRoute(0);
				var geocoder = new GClientGeocoder();
				var text;
				var step;
				var startpoint;
				var streetName;
				var color;
				var dom;
				
				var startpoints = new Array();
				var streetnames = new Array();
				var trafficstatuscolors = new Array();

				for(i=0; i< groute.getNumSteps(); i++)
				{
					step = groute.getStep(i);
					text = step.getDescriptionHtml();
				
					var dom = HTMLtoDOM("<p>" + text + "</p>");
					
					if(!dom.getElementsByTagName("b"))
					{
						alert("Descricao fora do formato esperado!");
						continue;
					}
					
					var node = dom.getElementsByTagName("b")[1] ? dom.getElementsByTagName("b")[1] : dom.getElementsByTagName("b")[0];  
					
					streetName = node.text || node.textContent;
				
					var index = streetName.indexOf("-");
					if( index > 0)
						streetName = streetName.substring(0,index);
					
					color = getColor(streetName);
					
					startpoint = step.getLatLng();
					
					startpoints.push(startpoint);
					streetnames.push(streetName);
					trafficstatuscolors.push(color);
				}

				var vertex;
				var myvertex = 0;
				var point;
				var pointlat;
				var pointlng;
				var streetlat;
				var streetlng;
				var currentStreet = 0;
				var linecolor = getColor(streetnames[currentStreet]);
				var mypolyline = new GPolyline({},linecolor);
				var polylines = new Array();
	
				for(vertex = 0; vertex < polyline.getVertexCount(); vertex++)
				{
					point = polyline.getVertex(vertex);
					mypolyline.insertVertex(myvertex,point);
					//alert("Pushed into " + streetnames[currentStreet] + " in position " + myvertex + " the vertex number " + vertex);
					myvertex++;
									
					for(street = currentStreet+1 ; street < startpoints.length ; street++)
					{
						pointlat = point.lat().toFixed(5);
						pointlng = point.lng().toFixed(5);
						streetlat = startpoints[street].lat().toFixed(5);
						streetlng = startpoints[street].lng().toFixed(5);
						
						if( (pointlat == streetlat) && (pointlng == streetlng) )
						{
							//alert("Nova rua: " + streetnames[currentStreet] + " | cor: " + linecolor + " | numvertices: " + mypolyline.getVertexCount());
							//alert("'" + streetnames[currentStreet] + "' -> " + translateNames(streetnames[currentStreet]));						
							polylines.push(mypolyline);
							currentStreet = street;
							myvertex = 0;
							linecolor = getColor(streetnames[currentStreet]);
							//alert("'" + streetnames[currentStreet] + "' ---> " + linecolor);
							mypolyline = new GPolyline({},linecolor);
						} 
					}

				}

				map = new google.maps.Map2(document.getElementById("map"));
				map.setCenter(new google.maps.LatLng(-22.92632, -43.235147), 16);
				
				//alert("Mapa criado e centralizado.");
				
				for(p = 0; p < polylines.length ; p++)				
					map.addOverlay(polylines[p]);
			
			});
		}	
	  
